package com.math.aistudykbr.service.impl;

import com.math.aistudykbr.exception.UserException;
import com.math.aistudykbr.mapper.UserMapper;
import com.math.aistudykbr.pojo.entity.User;
import com.math.aistudykbr.pojo.dto.UserDTO;
import com.math.aistudykbr.pojo.vo.UserVO;
import com.math.aistudykbr.service.UserService;
import com.math.aistudykbr.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    private  final JwtUtil jwtUtil;

    @Override
    public void checkUser(User user) throws UserException {
        // 1. 查询用户是否存在
        User selectUser = userMapper.selectUserByUsername(user.getUsername());
        if (selectUser != null) {
            throw new UserException("用户已存在");
        }
    }

    @Override
    public void saveUser(User user) throws UserException {
        // 1. 校验用户信息
        checkUser(user);

        // 2. 保存用户信息
        userMapper.saveUser(user);
    }

    @Override
    public UserVO selectUserByUsernameAndPassword(UserDTO userDTO) throws UserException {
        User user = userMapper.selectUserByUsername(userDTO.getUsername());
        if(user == null) {
            throw new UserException("用户不存在");
        }

        if (!user.getPassword().equals(userDTO.getPassword())) {
            throw new UserException("密码错误");
        }

        String token = jwtUtil.generateToken(user.getId());

        return UserVO.builder()
                .id(user.getId())
                .email(user.getEmail())
                .token(token)
                .build();
    }
}
